package com.gxy.learn.mybatisplus.common.exception;

import com.alibaba.fastjson.JSONObject;
import com.gxy.learn.mybatisplus.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 * 全局异常捕捉
 *
 * @author: Gao xueyong
 * Create at: 2022/02/17 下午17:18
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final String url = "url";
    private static final String errorMsg = "errorMsg";


    /**
     * 捕捉404异常
     *
     * @return
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result handle(HttpServletRequest req, NoHandlerFoundException ex) {
        log.error("{}:{},{}:{}", url, req.getRequestURI(), errorMsg, ex.getMessage(), ex);
        return Result.error("未知的请求！");
    }


    /**
     * 入参校验
     *
     * @param req
     * @param ex
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public Result badRequest(HttpServletRequest req, BindException ex) {
        log.error("{}:{},{}:{}", url, req.getRequestURI(), errorMsg, ex.getMessage(), ex);
        Map<String, String> result = new LinkedHashMap<>();
        for (FieldError fieldError : ex.getFieldErrors()) {
            result.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return Result.error("入参错误！", JSONObject.toJSON(result));
    }

    /**
     * 入参校验
     *
     * @param req
     * @param ex
     * @return
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result badRequest(HttpServletRequest req, MissingServletRequestParameterException ex) {
        log.error("{}:{},{}:{}", url, req.getRequestURI(), errorMsg, ex.getMessage(), ex);
        return Result.error(String.format("缺失入参[%s]!", ex.getParameterName()));
    }

    /**
     * 入参校验
     *
     * @param req
     * @param ex
     * @return
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(ConstraintViolationException.class)
    public Result badRequest(HttpServletRequest req, ConstraintViolationException ex) {
        log.error("{}:{},{}:{}", url, req.getRequestURI(), errorMsg, ex.getMessage(), ex);
        Map<String, String> result = new LinkedHashMap<>();
        for (ConstraintViolation cav : ex.getConstraintViolations()) {
            PathImpl path = (PathImpl) cav.getPropertyPath();
            result.put(path.getLeafNode().toString(), cav.getMessage());
        }
        return Result.error("入参错误！", JSONObject.toJSON(result));
    }


    /**
     * 捕捉其他所有异常
     *
     * @param req
     * @param ex
     * @return
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result globalException(HttpServletRequest req, Throwable ex) {
        log.error("{}:{},{}:{}", url, req.getRequestURI(), errorMsg, ex.getMessage(), ex);
        if (ex instanceof BindException) {
            return Result.error(String.format("入参错误！%s", ex.getMessage()));
        }
        return Result.error("请求出现异常！");
    }

}
